<template>
  <div class="ccui-app-container">
    <div class="ccui-advanced-search-wrapper ccui-clearfix">
      <el-search
        :formProp="formData"
        @search="search"
        @change="searchChange"
        :isShowSearch="isShowSearch"
        class="ccui-highsearch"
        :selectClear="true"
      >
        <div class="ccui-tab-wrapper">
          <el-button type="table-top-active" size="mini">
            <template>全部{{ `(${totalNum})` }}</template>
          </el-button>
        </div>
        <div class="ccui-extend-btn">
          <el-export-button
            class="export-button"
            @export-excel="exportDefault"
            @export-pdf="exportPdf"
          />

          <!-- @export-excel="exportFile('single')"
            @export-pdf="exportFile('all')" -->
        </div>
        <template slot="search">
          <el-input
            v-model="formData.paymentName"
            clearable
            searchLabel="付款申请单名称"
            placeholder="请输入付款申请单名称模糊查询"
            @blur="handleTrim('paymentName')"
          />
          <el-input
            v-model="formData.paymentCode"
            clearable
            searchLabel="付款申请单编号"
            placeholder="请输入付款申请编号模糊查询"
            @blur="handleTrim('paymentCode')"
          />
          <el-input
            v-model="formData.registerCode"
            clearable
            searchLabel="付款登记单编号"
            placeholder="请输入付款登记单编号模糊查询"
            @blur="handleTrim('registerCode')"
          />
          <el-input
            v-model="formData.contractCode"
            clearable
            searchLabel="合同编号"
            placeholder="请输入合同编号模糊查询"
            @blur="handleTrim('contractCode')"
          />
          <el-input
            v-model="formData.contractName"
            clearable
            searchLabel="合同名称"
            placeholder="请输入合同名称模糊查询"
            @blur="handleTrim('contractName')"
          />
          <el-select
            v-model="formData.paymentMode"
            placeholder="请选择付款方式"
            searchLabel="付款方式"
          >
            <el-option
              v-for="item in partyStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            v-model="formData.reportInOrgName"
            clearable
            searchLabel="填报单位"
            placeholder="请输入填报单位模糊查询"
            @blur="handleTrim('reportInOrgName')"
          />
          <el-input
            v-model="formData.payee"
            clearable
            searchLabel="收款人"
            placeholder="请输入收款人模糊查询"
            @blur="handleTrim('payee')"
          />
          <el-date-picker
            v-model="formData.reportTime"
            searchLabel="编制时间"
            clearable
            type="date"
            placeholder="请选择编制时间查询"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          />
        </template>
        <el-input
          v-model="formData.paymentName"
          clearable
          searchLabel="付款申请单名称"
          placeholder="请输入付款申请单名称模糊查询"
          @blur="handleTrim('paymentName')"
          slot="searchItem1"
        />
        <el-input
          v-model="formData.paymentCode"
          clearable
          searchLabel="付款申请单编号"
          placeholder="请输入付款申请编号模糊查询"
          @blur="handleTrim('paymentCode')"
          slot="searchItem2"
        />
        <el-input
          v-model="formData.registerCode"
          clearable
          searchLabel="付款登记单编号"
          placeholder="请输入付款登记单编号模糊查询"
          @blur="handleTrim('registerCode')"
          slot="searchItem3"
        />
        <el-input
          v-model="formData.contractCode"
          clearable
          searchLabel="合同编号"
          placeholder="请输入合同编号模糊查询"
          @blur="handleTrim('contractCode')"
          slot="searchItem4"
        />
        <el-input
          v-model="formData.contractName"
          clearable
          searchLabel="合同名称"
          placeholder="请输入合同名称模糊查询"
          @blur="handleTrim('contractName')"
          slot="searchItem5"
        />
        <el-select
          v-model="formData.paymentMode"
          placeholder="请选择付款方式"
          searchLabel="付款方式"
          slot="searchItem6"
        >
          <el-option
            v-for="item in partyStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-input
          v-model="formData.reportInOrgName"
          clearable
          searchLabel="填报单位"
          placeholder="请输入填报单位模糊查询"
          @blur="handleTrim('reportInOrgName')"
          slot="searchItem7"
        />
        <el-input
          v-model="formData.payee"
          clearable
          searchLabel="收款人"
          placeholder="请输入收款人模糊查询"
          @blur="handleTrim('payee')"
          slot="searchItem8"
        />
        <el-date-picker
          v-model="formData.reportTime"
          searchLabel="编制时间"
          clearable
          type="date"
          placeholder="请选择编制时间查询"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          slot="searchItem9"
        />
      </el-search>
    </div>
    <div class="ccui-multifunctional-table-wrapper">
      <el-table
        ref="multipleTable"
        :data="tableData"
        :fit="true"
        border
        class="ccui-multifunctional-table"
        max-height="20000"
        @cell-click="cellClick"
        :cell-style="cellStyle"
      >
        <template v-for="(table, index) in tableColumnData">
          <el-table-column
            :fixed="table.fixed || false"
            :type="table.type"
            :key="index"
            :label="table.label"
            :min-width="table.width"
            :prop="table.prop"
            :filters="table.filters"
            :formatter="formatterList[table.formatterName]"
            :show-overflow-tooltip="true"
            :align="table.align"
            :header-align="table.headerAlign || 'left'"
          ></el-table-column>
        </template>
      </el-table>
      <div class="ccui-table-footer" v-show="isShowPagination">
        <div id="ccui-paging">
          <el-pagination
            :total="totalNum"
            :page-size="getLocalPageSize()"
            :current-page="pageNoCode"
            :page-sizes="[10, 20, 50, 100, 200, 500]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            popper-class="ccui-paging-page-size-popper"
            @size-change="
              val => {
                handleSizeChange(val);
              }
            "
            @current-change="
              val => {
                handleCurrentChange(val);
              }
            "
          />
          <el-button
            class="ccui-pagination-btn"
            size="mini"
            type="default"
            @click="handleSizeChange('none')"
            >确定
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getSessionItem, setSessionItem } from "@/basa/utils";
import { qryStandingBook } from "./apis/index.js";
// import { listExport } from "@/config/utils/requestBlob";
// import blobTransfrom from "@/basa/utils/blobTansfrom";
const ExcelJS = require("exceljs");
import { saveAs } from "file-saver";
export default {
  name: "allList",
  data() {
    return {
      formData: {
        pageNo: 1,
        pageSize: 10
      },
      // 高级搜索相关
      isShowSearch: true,
      total: 0,
      tableData: [],
      content: "导出日期：",
      // 表格数据处理
      formatterList: {},
      // 分页相关
      isShowPagination: false,
      totalNum: 0,
      pageNoCode: 1,
      pageSizeCode: this.getLocalPageSize(),
      tableName: this.tableList.applicationAccountList,
      tableColumnData: [
        {
          label: "序号",
          type: "index",
          fixed: true
        },
        {
          label: "付款登记单编号",
          prop: "registerCode",
          width: "140",
          fixed: true
        },
        {
          label: "付款申请单编号",
          prop: "paymentCode",
          width: "140"
        },
        {
          label: "付款申请单名称",
          prop: "paymentName",
          width: "120"
        },
        {
          label: "合同编号",
          prop: "contractCode",
          width: "120"
        },
        {
          label: "合同名称",
          prop: "contractName",
          width: "120"
        },
        {
          label: "填报单位",
          prop: "reportInOrgName",
          width: "120"
        },
        {
          label: "收款人",
          prop: "payee",
          width: "100"
        },
        {
          label: "申请付款金额",
          prop: "paymentMoney",
          width: "100"
        },
        {
          label: "登记付款金额",
          prop: "registerPrice",
          width: "100"
        },
        {
          label: "币种",
          prop: "currencyName",
          width: 100
        },
        {
          label: "编制人",
          prop: "reportUsername",
          width: 70
        },
        {
          label: "编制日期",
          prop: "reportTimeStr",
          width: 100
        }
      ],
      partyStatus: [
        {
          label: "银行承兑",
          value: "1"
        },
        {
          label: "商业承兑",
          value: "2"
        },
        {
          label: "供应链金融",
          value: "3"
        },
        {
          label: "现金",
          value: "4"
        }
      ],
      paymentStatus: [
        {
          label: "预付",
          value: "1"
        },
        {
          label: "应付",
          value: "2"
        }
      ]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 表格数据获取
    getList(reqObj) {
      let obj = {};
      obj = typeof reqObj == "object" ? reqObj : obj;
      obj.pageNo = this.pageNoCode;
      obj.pageSize = this.pageSizeCode;
      obj.isShowPageLoading = true;
      obj.loadingMessage = "加载中,请稍等...";
      qryStandingBook(obj).then(res => {
        console.log(res.data.data.rows);
        if (res.data.data.rows.length) {
          this.tableData = res.data.data.rows.map(n => ({
            ...n,
            // 付款金额
            paymentMoney:
              n.paymentMoney == "" ? "" : Number(n.paymentMoney).toFixed(2),
            // 登记付款金额
            registerPrice:
              n.registerPrice == "" ? "" : Number(n.registerPrice).toFixed(2)
          }));
        } else {
          this.tableData = [];
        }
        this.totalNum = res.data.data.recordsTotal; //总记录条数
        this.pageNoCode = res.data.data.pageNo; // 当前页
        this.tableData.length == 0
          ? (this.isShowPagination = false)
          : (this.isShowPagination = true);
      });
    },
    // 高级搜索切换清空
    searchChange() {
      this.formData = {
        pageNo: 1,
        pageSize: 10
      };
    },
    // 重置
    resetForm() {
      this.formData = {
        pageNo: this.pageNoCode,
        pageSize: this.pageSizeCode
      };
    },
    // 单元格点击跳转详情
    cellClick(r, column) {
      console.log(r);
      if (column.label === "付款登记单编号" && r.registerCode !== "") {
        // add-新增 look-查看 edit-编辑
        const params = {
          id: r.rid,
          status: "look"
        };
        this.$router.push(
          `/paymentManagement/applicationChange/detail/${JSON.stringify(
            params
          )}`
        );
      }
      if (column.label === "付款申请单编号" && r.paymentCode !== "") {
        // add-新增 look-查看 edit-编辑
        const params = {
          id: r.pid,
          status: "look"
        };
        this.$router.push(
          `/paymentManagement/application/detail/${JSON.stringify(params)}`
        );
      }
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (
        column.label == "付款申请单编号" ||
        column.label == "付款登记单编号"
      ) {
        return { color: "#0089EF", cursor: "pointer" };
      }
      if (column.label == "申请付款金额" || column.label == "登记付款金额") {
        return { textAlign: "right" };
      }
    },
    // 获取默认分页
    getLocalPageSize() {
      return (
        getSessionItem("pageSize", this.tableList.applicationAccountList) || 10
      );
    },
    // 显示条数更改
    handleSizeChange(val) {
      this.pageNoCode = 1;
      console.log("fasfasfasf");
      if (val !== "none") {
        this.pageSizeCode = val;
        setSessionItem("pageSize", this.tableName, val);
      }
      this.getList();
    },
    // 当前页码更改
    handleCurrentChange(val) {
      let searchFormData = getSessionItem("pageNo", this.tableName) || {};
      setSessionItem("pageNo", this.tableName, {
        pageNo: val,
        searchForm: searchFormData.searchForm || {}
      });
      this.formDataSearch = {
        ...this.formDataSearch,
        ...searchFormData.searchForm
      };
      // 跳转翻页都会调这个方法
      this.pageNoCode = val;
      this.getList(this.formDataSearch);
    },
    // 高级搜索
    search(searchData) {
      this.pageNoCode = 1;
      this.formDataSearch = JSON.parse(JSON.stringify(searchData));
      this.localSearchData = JSON.parse(JSON.stringify(searchData));
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
      this.getList(this.formDataSearch);
    },
    getDate() {
      let date = new Date();
      let seperator1 = "-";
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },

    // 导出
    // async exportFile(type) {
    //   const obj = {
    //     ...this.formData,
    //     type: "paymentRegister/accountExport",
    //     pageNo: type === "all" ? 1 : this.pageNoCode,
    //     pageSize: type === "all" ? 3000 : this.pageSizeCode
    //   };
    //   blobTransfrom(await listExport(obj));
    // },

    //导出全部
    exportPdf() {
      let obj = {};
      obj.pageSize = 5000;
      obj.pageNo = 1;
      qryStandingBook(obj).then(res => {
        if (res.data.data.recordsTotal > 5000) {
          this.$message({
            message: "暂不支持5000行以上大批量数据导出",
            type: "warning",
            offset: document.documentElement.clientHeight / 2 - 21
          });
        } else {
          console.log(res.data.data.rows);
          const arr = res.data.data.rows.map(n => ({
            ...n,
            // 付款金额
            paymentMoney:
              n.paymentMoney == "" ? "" : Number(n.paymentMoney).toFixed(2),
            // 登记付款金额
            registerPrice:
              n.registerPrice == "" ? "" : Number(n.registerPrice).toFixed(2)
          }));
          this.exportDefaultAll(arr);
        }
      });
    },
    //导出当前
    async exportDefault() {
      const wb = new ExcelJS.Workbook();
      const ws1 = wb.addWorksheet("付款台账");
      ws1.views = [{ state: "frozen", ySplit: 3 }];
      ws1.addRow(["付款台账"]);
      ws1.addRow([this.content + this.getDate()]);
      ws1.addRow([
        "序号",
        "付款登记单编号",
        "付款申请单编号",
        "付款申请单名称",
        "合同编号",
        "合同名称",
        "填报单位",
        "收款人",
        "申请付款金额",
        "登记付款金额",
        "币种",
        "编制人"
      ]);
      ws1.mergeCells("A1:M1");
      ws1.mergeCells("A2:M2");

      ws1.columns = [
        { key: "index", width: 5 },
        { key: "registerCode", width: 35 },
        { key: "paymentCode", width: 35 },
        { key: "paymentName", width: 35 },
        { key: "contractCode", width: 35 },
        { key: "contractName", width: 35 },
        { key: "reportInOrgName", width: 35 },
        { key: "payee", width: 35 },
        { key: "paymentMoney", width: 35 },
        { key: "registerPrice", width: 35 },
        { key: "currencyName", width: 35 },
        { key: "reportUsername", width: 35 }
      ];
      this.tableData.forEach((item, index) => {
        ws1.addRow([
          index + 1,
          item.registerCode,
          item.paymentCode,
          item.paymentName,
          item.contractCode,
          item.contractName,
          item.reportInOrgName,
          item.payee,
          item.paymentMoney,
          item.registerPrice,
          item.currencyName,
          item.reportUsername
        ]);
      });
      ws1.getRow(3).font = { bold: true, color: { argb: "000000" } };
      ws1.getRow(3).fill = { color: { argb: "000000" } };
      ws1.getRow(1).font = { bold: true, color: { argb: "000000" } };
      ws1.getRow(1).fill = { color: { argb: "000000" } };
      ws1.getColumn(5).alignment = { vertical: "middle", horizontal: "left" };
      ws1.getColumn(6).alignment = { vertical: "middle", horizontal: "left" };
      ws1.getColumn(5).alignment = { vertical: "middle", horizontal: "left" };
      ws1.getRow(1).alignment = { vertical: "middle", horizontal: "center" };
      ws1.getRow(2).alignment = { vertical: "middle", horizontal: "left" };
      const buf = await wb.xlsx.writeBuffer();
      saveAs(new Blob([buf]), "付款台账.xlsx");
    },
    //导出全部
    async exportDefaultAll(arr) {
      const wb = new ExcelJS.Workbook();
      const ws1 = wb.addWorksheet("付款台账");
      ws1.views = [{ state: "frozen", ySplit: 3 }];
      ws1.addRow(["付款台账"]);
      ws1.addRow([this.content + this.getDate()]);
      ws1.addRow([
        "序号",
        "付款登记单编号",
        "付款申请单编号",
        "付款申请单名称",
        "合同编号",
        "合同名称",
        "填报单位",
        "收款人",
        "申请付款金额",
        "登记付款金额",
        "币种",
        "编制人"
      ]);
      ws1.mergeCells("A1:M1");
      ws1.mergeCells("A2:M2");

      ws1.columns = [
        { key: "index", width: 5 },
        { key: "registerCode", width: 35 },
        { key: "paymentCode", width: 35 },
        { key: "paymentName", width: 35 },
        { key: "contractCode", width: 35 },
        { key: "contractName", width: 35 },
        { key: "reportInOrgName", width: 35 },
        { key: "payee", width: 35 },
        { key: "paymentMoney", width: 35 },
        { key: "registerPrice", width: 35 },
        { key: "currencyName", width: 35 },
        { key: "reportUsername", width: 35 }
      ];
      arr.forEach((item, index) => {
        ws1.addRow([
          index + 1,
          item.registerCode,
          item.paymentCode,
          item.paymentName,
          item.contractCode,
          item.contractName,
          item.reportInOrgName,
          item.payee,
          item.paymentMoney,
          item.registerPrice,
          item.currencyName,
          item.reportUsername
        ]);
      });
      ws1.getRow(3).font = { bold: true, color: { argb: "000000" } };
      ws1.getRow(3).fill = { color: { argb: "000000" } };
      ws1.getRow(1).font = { bold: true, color: { argb: "000000" } };
      ws1.getRow(1).fill = { color: { argb: "000000" } };
      ws1.getColumn(5).alignment = { vertical: "middle", horizontal: "left" };
      ws1.getColumn(6).alignment = { vertical: "middle", horizontal: "left" };
      ws1.getColumn(5).alignment = { vertical: "middle", horizontal: "left" };
      ws1.getRow(1).alignment = { vertical: "middle", horizontal: "center" };
      ws1.getRow(2).alignment = { vertical: "middle", horizontal: "left" };
      const buf = await wb.xlsx.writeBuffer();
      saveAs(new Blob([buf]), "付款台账.xlsx");
    },

    // 清空名称空格
    handleTrim(key) {
      if (this.formData[key] == undefined) return;
      this.$set(
        this.formData,
        key,
        this.formData[key].replace(/(^\s*)|(\s*)$/g, "")
      );
    }
  },
  activated() {
    this.pageNoCode = 1;
    this.getList();
  }
};
</script>

<style scoped lang="scss">
.ccui-tab-wrapper {
  padding-top: 0px !important;
}

/deep/ .el-searchs-box {
  width: 406px !important;
}
/deep/
  .ccui-advanced-search-wrapper
  .el-search
  .el-searchs-bottom
  .el-form-item
  .el-form-item__label {
  width: 117px !important;
}
/deep/ .classR {
  text-align: right;
}
</style>
